package com.example.mes_sys.jwt;

import com.example.mes_sys.vo.UserDetailsVo;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;

/**
 * jtw工具类
 */
@Component
public class JwtTokenProvider {
    private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class);
    //私钥
    private static final String JWT_SECRET = "PdtRVjQ6QfMFFi6Jw3k6C+o1H4rirF2yEXU39V/GMAgseVzXoCBqhMLppJgEif25bXkZwzflB5l3WsrBPdwBVQ==";
    //过期时间
    private static final long JWT_EXPIRATION = 86400000;

    //生成签名用的 Key
    private Key key(){
        return Keys.hmacShaKeyFor(JWT_SECRET.getBytes());
    }

    /**
     * 生成 JWT Token
     * @param authentication 认证信息
     * @return JWT Token
     */
    public String generateToken(Authentication authentication){
        UserDetailsVo userPrincipal = (UserDetailsVo) authentication.getPrincipal();

        Date now = new Date();
        Date expiryLocalDateTime = new Date(now.getTime() + JWT_EXPIRATION);

        return Jwts.builder()
                .setSubject(Long.toString(userPrincipal.getId()))
                .setIssuedAt(new Date())
                .setExpiration(expiryLocalDateTime)
                .signWith(key(), SignatureAlgorithm.HS512)
                .compact();
    }

    /**
     * 从 Token 中获取用户 ID
     * @param token JWT Token
     * @return 用户 ID
     */
    public Long getUserIdFromJWT(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(key())
                .build()
                .parseClaimsJws(token)
                .getBody();

        return Long.parseLong(claims.getSubject());
    }

    /**
     * 验证 Token 是否有效
     * @param authToken JWT Token
     * @return 是否有效
     */
    public boolean valiLocalDateTimeToken(String authToken) {
        try {
            Jwts.parserBuilder().setSigningKey(key()).build().parseClaimsJws(authToken);
            return true;
        } catch (MalformedJwtException ex) {
            logger.error("Invalid JWT token");
        } catch (ExpiredJwtException ex) {
            logger.error("Expired JWT token");
        } catch (UnsupportedJwtException ex) {
            logger.error("Unsupported JWT token");
        } catch (IllegalArgumentException ex) {
            logger.error("JWT claims string is empty");
        }
        return false;
    }


}
